<!-- Horizontal Form -->
<div class="box box-info">
    <div class="box-header with-border">
        <h3 class="box-title">商品添加</h3>
        <h3 class="msg"></h3>
    </div>
    <!-- /.box-header -->
    <!-- form start -->
    <form class="form-horizontal">
        <div class="box-body">
            <div class="form-group">
                <label for="productNameId" class="col-sm-2 control-label">商品名称</label>
                <div class="col-sm-8">
                    <input type="text" name="productName" class="form-control" id="productNameId"
                    placeholder="不能为空" required=true>
                </div>
            </div>
            <div class="form-group">
                <label for="advantageId" class="col-sm-2 control-label">卖点信息</label>
                <div class="col-sm-8">
                    <input type="text" name="advantage" class="form-control" id="advantageId"
                           placeholder="没有卖点的商品是无法卖出的">
                </div>
            </div>
            <div class="form-group">
                <label for="promotionId" class="col-sm-2 control-label">促销信息</label>
                <div class="col-sm-8">
                    <input type="text" name="promotion" class="form-control" id="promotionId"
                           placeholder="商品促销才可以大卖哟">
                </div>
            </div>
            <div class="form-group">
                <label for="categoryId" class="col-sm-2 control-label">商品类型</label>
                <div class="col-sm-8" id="categoryId"></div>
            </div>
            <div class="form-group">
                <label for="imageId" class="col-sm-2 control-label">商品图片</label>
                <div class="col-sm-8" id="imageId"></div>
            </div>
            <div class="form-group">
                <label for="descId" class="col-sm-2 control-label">商品描述</label>
                <div class="col-sm-8" id="descId">
                    <textarea class="form-control" placeholder="请在这里添加商品描述"></textarea>
                </div>
            </div>

        </div>
        <!-- /.box-body -->
        <div class="box-footer">
            <button type="button" class="btn btn-default btn-cancel">退出</button>
            <button type="button" class="btn btn-info pull-right btn-save">保存</button>
        </div>
        <!-- /.box-footer -->
    </form>

</div>
<script type="text/javascript" src="bower_components/ztree/jquery.ztree.all.min.js"></script>
<script type="text/javascript" src="bower_components/layer/layer.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        //页面加载完成以后加载角色信息并初始化页面
        doLoadCategorys();
        //事件注册
        $(".box-footer")
            .on("click", ".btn-cancel", doCancel)   //触发取消
            .on("click", ".btn-save", doSaveOrUpdate);  //触发新增/修改
    });

    //取消
    function doCancel() {
        $("#mainContentId").removeData("rowData");
        $("#mainContentId").load("/modules/sys/item_list.html");
    }

    //新增/修改
    function doSaveOrUpdate() {
        let rowData = $("#mainContentId").data("rowData"); //读取修改的数据
        //1.获取表单数据
        let data = doGetEditFormData();
        if (rowData) data.id = rowData.id; //如果有数据就是进行修改,id等于选中的id
        //用户输入校验
        if(data.pdName==""){
            alert("商品名称必须输入!");return;
        }
        if(data.categoryId==null){
            alert("必须选择一个商品类别!");return;
        }
        if(!rowData){
            data.saleState=0;
        }
        //2.发起异步请求
        let url = `${baseUrl}/shoppingback/ddProductInfo`;
        let method = rowData ? "put" : "post";  //如果有数据就是put,没数据就是post
        $.ajax({
            method: method,
            url: url,
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            crossDomain: true,
            xhrFields: {withCredentials: true},
            data: JSON.stringify(data),
            contentType: "application/json",
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    alert(result.msg);
                    doCancel();
                } else {
                    alert(result.msg);
                }
            }
        })
    }

    //添加用户:读取输入的数据
    function doGetEditFormData() {
        //获取用户输入的数据
        let params = {
            pdName: $("#productNameId").val(),
            advantage: $("#advantageId").val(),
            promotion: $("#promotionId").val(),
            categoryId: $("input[name='category']:checked").val(),
            pdImage: $("#imageId").val(),
            desc: $("#descId").val(),
        }
        return params;
    }

    //读取商品类别信息,并载入修改信息
    function doLoadCategorys() {
        let url = `${baseUrl}/shoppingback/ddCategoryInfo`;
        $.ajax({
            url, crossDomain: true, xhrFields: {withCredentials: true},
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    doInitPageCategory(result.data);//显示角色按钮
                    doInitFormData();//修改操作:载入表单数据
                } else {
                    alert(result.msg);
                }
            }
        })
    }

    //修改用户:读取表单数据
    function doInitFormData() {
        let data = $("#mainContentId").data("rowData");
        if (!data) return; //如果不是修改则返回
        //初始化用户信息
        $("#productNameId").val(data.pdName);
        $("#advantageId").val(data.advantage);
        $("#promotionId").val(data.promotion);
        $("#imageId").val(data.image);
        $("#descId").val(data.desc);
        //初始化用户类别信息
        let id = data.categoryId;
        $(`#categoryId input[value=${id}]`).prop("checked", true); //根据id进行默认勾选


    }

    //显示类型按钮
    function doInitPageCategory(data) {//List<CheckBox>
        //1.获取商品类型要显示的位置对象
        let div = $("#categoryId");
        div.empty();
        //2.迭代数据，将数据追加到div
        let input = `<input type='radio' name='category' value='[id]'> [name]   ` //载入单选按钮
        console.log(data);
        data.forEach(item => {
            //记住每次replace时都会产生一个新的字符串对象
            var newInput =
                input.replace("[id]", item.id)
                    .replace("[name]", item.categoryName);
            div.append(newInput)    //插入单选按钮
        });
    }

</script>
    
    
    
    
    
    
    